<template>
  <div class="recommend-course">
    <section class="search-content">
      <el-row :gutter="4" type="flex" justify="start">
        <el-col :span="24">
          <el-select v-model="option" @change="handleFilter"><el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"/></el-select>
          <el-input v-model="title" placeholder="标题" style="width:150px" @keyup.enter.native="handleFilter"/>
          <el-input v-model="creator" placeholder="创建者" style="width:150px" @keyup.enter.native="handleFilter"/>
          <el-button type="primary" @click="handleFilter">搜索</el-button>
          <el-button size="medium" type="info" @click="clearParams">清空</el-button>
        </el-col>
      </el-row>
    </section>
    <all-table
      v-loading="listLoading"
      :table-label="tableLabel"
      :table-data="tableData.slice((currentpage-1)*pagesize,currentpage*pagesize)"
    >
      <el-table-column slot="button" label="操作" prop="manage" align="center" min-width="20">
        <template slot-scope="scope">
          <el-button type="primary" @click="setRecommend(scope)">设置序号</el-button>
          <el-button type="primary" @click="cancelRecommend(scope)">取消推荐</el-button>
        </template>
      </el-table-column>
    </all-table>

    <!-- 推荐序号设置 -->
    <el-dialog :visible.sync="dialogVisible" title="设置推荐课程" width="580px">
      <el-form ref="sequence" :model="sequence" label-width="120px" :rules="rules">
        <el-form-item label="序号" prop="num">
          <el-input v-model="sequence.num" style="width: 280px"/>
          <br>请输入长度不能超过8位的整数
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateCourse">保 存</el-button>
      </div>
    </el-dialog>

    <pagination
      :total="total"
      :current-page="currentpage"
      :page-size="pagesize"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
  </div>
</template>

<script>
  import allTable from '@/components/Eltable'
  import Pagination from '@/components/Pagination'
  import {fetchList, updateCourse} from '@/api/subject/course'
  import {getTenantId} from '@/utils/auth'

  export default {
    components: {
      allTable,
      Pagination
    },
    data() {
      return {
        dialogVisible: false,
        sequence: {
          entity: {},
          num: ''
        },
        total: 0,
        currentpage: 1,
        pagesize: 10,
        listLoading: false,
        title: '',
        creator: '',
        option: '',
        options: [{label: '课程分类', value: ''}, {label: '普通课程', value: 'normal'}, {label: '直播课程', value: 'live'}, {label: '公开课', value: 'open'}, {label: '直播公开课', value: 'liveOpen'}],
        tableLabel: [{label: '顺序号', width: '5', prop: 'recommendedSeq'}, {label: '课程名称', width: '15', prop: 'title'}, {label: '创建者', width: '10', prop: 'userName'}, {label: '推荐时间', width: '10', prop: 'recommendedTimeStr'}],
        tableData: [],
        listFilter: [],
        rules: {
          num: [
            {required: true, message: '必填信息', trigger: 'blur'},
            {min: 1, max: 8, message: '长度不能超过8位', trigger: 'blur'},
            {pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入长度不能超过8位的整数'}
          ]
        }
      }
    },
    mounted() {
      this.getData()
    },
    methods: {
      setRecommend(scope) {
        this.dialogVisible = true;
        this.sequence.entity = scope.row
      },
      updateCourse() {
        this.$refs.sequence.validate((valid) => {
          if (valid) {
            this.dialogVisible = false;
            this.sequence.entity.recommended = 1;
            if (!this.sequence.num) this.sequence.num = 100;
            this.sequence.entity.recommendedSeq = this.sequence.num;
            this.sequence.entity.recommendedTime = new Date();
            updateCourse(this.sequence.entity).then(response => {
              this.$notify({
                title: '成功',
                message: '该课程已设置为推荐！',
                type: 'success',
                duration: 2000
              });
              this.getData();
              this.tableData.map(item => {
                if (item.recommendedTime) item.recommendedTimeStr = new Date(item.recommendedTime).toLocaleString().substring(0, 10).replace(/[\u4e00-\u9fa5]/g, '')
              })
            })
          } else {
            console.log('error submit!!');
            return false
          }
        })
      },
      cancelRecommend(scope) {
        this.$confirm(`确定取消推荐吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          scope.row.recommended = 0;
          scope.row.recommendedSeq = 100;
          scope.row.recommendedTime = '';
          updateCourse(scope.row);
          this.getData();
          this.$notify({
            title: '成功',
            message: '推荐已取消！',
            type: 'success',
            duration: 2000
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '放弃取消推荐'
          })
        })
      },
      handleSizeChange(val) {
        this.currentpage = 1;
        this.pagesize = val.value;
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
        this.getData()
      },
      handleCurrentChange(val) {
        this.currentpage = val.value;
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
        this.getData()
      },
      handleFilter() {
        this.getData()
      },
      clearParams() {
        this.option = '';
        this.title = '';
        this.creator = '';
        this.getData()
      },
      getData() {
        this.listLoading = true;
        const params = {};
        params.page = this.currentpage;
        params.pageSize = this.pagesize;
        params.name = this.title;
        params.creator = this.creator;
        params.courseType = this.option;
        params.recommended = '1';
        params.tenantId = getTenantId();
        console.log(params);
        fetchList(params).then(response => {
          response.data.items.map(item => {
            if (item.recommendedTime) item.recommendedTimeStr = new Date((item.recommendedTime)).toLocaleString().substring(0, 10).replace(/[\u4e00-\u9fa5]/g, '')
          });
          this.total = response.data.items.length;
          this.tableData = response.data.items;
          this.listLoading = false
        })
      }
    }
  }
</script>

<style lang="scss">
  .recommend-course {
    .cell {
      div {
        font-size: 14px;
        color: #606266;
      }
    }
  }
</style>
